package config

import (
	. "TaylorTest/app"
	. "TaylorTest/model"
	"encoding/json"
	"strconv"
)

var filePath string = "/appdata/periods.json"

func GetPeriodList(context *Context) {
	periods := getPeriods()
	context.Json(periods)
}
func AddPeriod(context *Context) {
	context.Request.ParseForm()
	periodid, _ := strconv.Atoi(context.Request.Form["periodid"][0])
	periodname := context.Request.Form["periodname"][0]
	period := &Period{PeriodID: periodid, PeriodName: periodname}
	addPeriod(period)
	context.Success()
}

func UpdatePeriod(context *Context) {
	context.Request.ParseForm()
	periodid, _ := strconv.Atoi(context.Request.Form["periodid"][0])
	periodname := context.Request.Form["periodname"][0]
	period := &Period{PeriodID: periodid, PeriodName: periodname}
	updatePeriod(period)
	context.Success()
}

func DeletePeriod(context *Context) {
	context.Request.ParseForm()
	periodid, _ := strconv.Atoi(context.Request.Form["periodid"][0])
	deletePeriod(periodid)
	context.Success()
}

func getPeriods() []Period {
	filtBytes := FileReadAll(filePath)
	res := &[]Period{}
	json.Unmarshal(filtBytes, &res)
	return *res
}
func addPeriod(period *Period) {
	periods := getPeriods()
	periods = append(periods, *period)
	jsonBytes, _ := json.Marshal(periods)
	FileWriteString(filePath, string(jsonBytes))
}
func updatePeriod(period *Period) {
	periods := getPeriods()
	for i := 0; i < len(periods); i++ {
		if periods[i].PeriodID == period.PeriodID {
			periods[i] = *period
		}
	}
	jsonBytes, _ := json.Marshal(periods)
	FileWriteString(filePath, string(jsonBytes))
}

func deletePeriod(periodid int) {
	periods := getPeriods()
	for i := 0; i < len(periods); i++ {
		if periods[i].PeriodID == periodid {
			periods = append(periods[0:i], periods[i+1:]...)
			break
		}
	}
	jsonBytes, _ := json.Marshal(periods)
	FileWriteString(filePath, string(jsonBytes))
}
